package com.sl.core.engine.meta.valuemeta;

import cn.hutool.core.collection.CollUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.value.ValueMetaBase;
import org.apache.hop.core.row.value.ValueMetaPlugin;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;


@ValueMetaPlugin(id = ValueMetaObject.TYPE, name = "Object", description = "OBJECT")
public class ValueMetaObject extends ValueMetaBase implements ObjArrayMetaInterface {

    private List<IValueMeta> fields;

    public static final String TYPE = "11";


    public ValueMetaObject() {
        this(null);
    }

    public ValueMetaObject(String name) {
        super(name, Integer.parseInt(TYPE), -1, -1);
    }

    @Override
    public Object getNativeDataType(Object object)   {
        return object;
    }

    @Override
    public Class<?> getNativeDataTypeClass()   {
        return Object.class;
    }


    @Override
    public List<IValueMeta> getFields() {
        return this.fields;
    }

    @Override
    public void setFields(List<IValueMeta> fields) {
        synchronized (this) {
            this.fields = new ArrayList<>();
        }
        this.fields.addAll(fields);
    }

    @Override
    public void addField(IValueMeta childMete) {
        if (fields == null) {
            synchronized (this) {
                if (fields == null) {
                    fields = new ArrayList<>();
                }
            }
        }
        fields.add(childMete);
    }

    @Override
    public void addFields(List<IValueMeta> childMete) {
        if (fields == null) {
            synchronized (this) {
                if (fields == null) {
                    fields = new ArrayList<>();
                }
            }
        }
        fields.addAll(childMete);
    }

    @Override
    public IValueMeta getField(String fieldName) {
        if (CollUtil.isEmpty(fields)) {
            return null;
        }
        for (IValueMeta field : fields) {
            if (StringUtils.equals(field.getName(), fieldName)) {
                return field;
            }
        }
        return null;
    }

    public IValueMeta putField(IValueMeta valueMetaInterface) {
        if (CollUtil.isEmpty(fields)) {
            return null;
        }
        ListIterator<IValueMeta> iterator = fields.listIterator();
        while (iterator.hasNext()) {
            IValueMeta field = iterator.next();
            if (StringUtils.equals(field.getName(), valueMetaInterface.getName())) {
                iterator.remove();
                iterator.add(valueMetaInterface);
                return field;
            }
        }
        fields.add(valueMetaInterface);
        return null;
    }

}
